package com.xihuanjun.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageUtils {

    //创建一个robot对象
    static Robot robut;

    static {
        try {
            robut = new Robot();
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 截取屏幕的一块，存储到磁盘
     * @param x
     * @param y
     * @param width
     * @param height
     * @param saveFileName
     * @param zoom 缩放比例，传1是原图，传2是放大两倍
     * @throws IOException
     */
    public static void capture(int x,int y,int width,int height,String saveFileName,int zoom) throws IOException {

        //创建该分辨率的矩形对象
        Rectangle screenRect=new  Rectangle(x,y,width,height);
        //根据这个矩形截图
        BufferedImage bufferedImage=robut.createScreenCapture(screenRect);
        BufferedImage newImage = resizeImage(bufferedImage,bufferedImage.getWidth()*zoom,bufferedImage.getHeight()*zoom);
        //保存截图
        File file=new File(saveFileName);
        ImageIO.write(newImage,"png",file);
    }

    public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
        Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_AREA_AVERAGING);
        BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        outputImage.getGraphics().drawImage(resultingImage, 0, 0, null);
        return outputImage;
    }


}
